package cn.idongjia.task.client.support;

import cn.idongjia.task.client.constant.TaskPrefix;
import cn.idongjia.task.client.constant.TaskTypes;
import cn.idongjia.task.common.constant.Excuters;
import cn.idongjia.task.common.task.ExcuteType;
import cn.idongjia.task.common.task.FaultType;
import cn.idongjia.task.common.task.Task;
import cn.idongjia.task.common.task.Type;
import cn.idongjia.task.provider.common.ITaskProvider;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import javax.annotation.Resource;
import java.util.*;
import static cn.idongjia.task.client.constant.Const.USER_MAJIA;
import static cn.idongjia.task.client.constant.ExtParmName.PID;
import static cn.idongjia.task.client.constant.ExtParmName.UID;

public class LikeTask {
    private static final Logger LOGGER = LoggerFactory.getLogger(LikeTask.class);

    private static final Random RANDOM = new Random();

    @Resource
    private JedisPool pool;
    @Resource
    private ITaskProvider taskProvider;

    private int maxNum;

    private int maxTime;

    @Value("${default.avatar.img}")
    private String defaultAvatar;

    public void addCollect(final long pid) {
        try {
            try (Jedis jedis = pool.getResource()) {
                long count = jedis.scard(USER_MAJIA);
                int num = RANDOM.nextInt((int) (maxNum > count ? count : maxNum));
                if (num < 1) {
                    num = 1;
                }
                List<String> users = jedis.srandmember(USER_MAJIA, num);
                LOGGER.debug("auto collect task : [ majia_number: " + num + ", pid : " + pid + "]");
                for(String uid : users){
                    int delay = RANDOM.nextInt(maxTime)*1000;
                    Task task = new Task();
                    task.setExcuteType(ExcuteType.JAVA);
                    task.setExtParam(PID,String.valueOf(pid));
                    task.setExtParam(UID,String.valueOf(uid));
                    task.setExuterName(Excuters.DONGJIA_EXCUTER);
                    task.setFaultType(FaultType.LOST);
                    task.setTaskType(TaskTypes.AUTH_COLLECT);
                    task.setTriggerTime(System.currentTimeMillis() + delay);
                    task.setTaskId(TaskPrefix.AUTO_COLLECT + pid + "_" + uid);
                    task.setType(Type.TIMING);
                    taskProvider.submitTask(task);
                }
            }
        } catch (Exception e) {
            LOGGER.debug("add post likes has an error:[{}]", e);
        }
    }

    public void setDefaultAvatar(String defaultAvatar) {
        this.defaultAvatar = defaultAvatar;
    }

    public void setMaxNum(int maxNum) {
        this.maxNum = maxNum;
    }

    public void setMaxTime(int maxTime) {
        this.maxTime = maxTime;
    }
}
